/**
 * @description 待办事项
 * @date 2022-03-17
 */
const Router = require('koa-router')
const todoRouter = new Router()

const Todo = require('../models/todo')

const { Op } = require('sequelize')
const {
  getQuery,
  getBody,
  httpHandler,
  toJSON,
  getCurDateTime,
} = require('../utils/global')
const {
  TODO_CATEGORY_ALL,
  TODO_CATEGORY_FINISHED,
} = require('../utils/globalParams')

// 新增
todoRouter.post('/add', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const body = getBody(ctx)
    // 默认 'Work' 类型
    body.category !== '' ? body.category : (body.category = 'Work')
    // 默认未完成
    body.isFinish = '否'
    // 创建时间默认当前服务器时间
    body.createDate = getCurDateTime()

    // 注意！一定要试用 await，否则可能出现：在未插入数据的时候，就调用了get接口获取新数据，导致无法获取最新数据
    await Todo.create({
      content: body.content,
      category: body.category,
      tag: body.tag,
      isFinish: body.isFinish,
      createDate: body.createDate,
    })
  })
})

// 获取待办列表
todoRouter.get('/list', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const { category } = getQuery(ctx)

    // 过滤条件
    let where = {}

    switch (category) {
      // 'Finished'分类查已完成
      case TODO_CATEGORY_FINISHED:
        where = {
          isFinish: {
            [Op.eq]: '是',
          },
        }
        break
      // 'All'分类查询未完成的所有数据
      case TODO_CATEGORY_ALL:
        where = {
          isFinish: {
            [Op.eq]: '否',
          },
        }
        break
      // 其他按分类查询
      default:
        where = {
          category: {
            [Op.eq]: category,
          },
          isFinish: {
            [Op.eq]: '否',
          },
        }
        break
    }

    const data = await Todo.findAll({
      where,
    })
    let res = toJSON(data, null, 2)
    return res
  })
})

// 删除
todoRouter.delete('/delete', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const { id } = getQuery(ctx)

    await Todo.destroy({
      where: {
        id: id,
      },
    })
  })
})

// 更新
todoRouter.put('/update', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const body = getBody(ctx)

    await Todo.update(body, {
      where: {
        id: body.id,
      },
    })
  })
})

// 完成
todoRouter.put('/finish', async (ctx, next) => {
  ctx.body = await httpHandler(async () => {
    const body = getBody(ctx)

    await Todo.update(
      {
        isFinish: '是',
        finishDate: getCurDateTime(),
      },
      {
        where: {
          id: body.id,
        },
      }
    )
  })
})

module.exports = todoRouter
